package com.jweb.framework.core.channel;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.jweb.framework.core.support.AntPathMatcher;
import com.jweb.framework.core.support.PathMatcher;

public abstract class URIEndpointMapping<Request,Response> extends AbstractEndpointMapping<Request, Response>{
	
	private PathMatcher pathMatcher ;
	
	private Map map ;
	
	public URIEndpointMapping(){
		pathMatcher = new AntPathMatcher();
	}
	
	public void setMapping(Map mapping){
		map = mapping ;
	}
	
	protected Endpoint doMapping(ChannelContext<Request, Response> channelContext){
		
		if(map == null){
			return null;
		}
		String s = getURIString(channelContext);  // s="/httpJson.json/smsmopush"
		
		
		int index = s.indexOf("smsmopush");

		if(index > 5) {
			s = s.substring(0, index-1);
			logger.debug("smsmopush request = " + s);
		}
		
		Endpoint endpoint = (Endpoint) map.get(s);
		if(endpoint != null){
			return endpoint; 
		}
		
		for(Iterator iterator = map.entrySet().iterator();iterator.hasNext();){
			Map.Entry entry = (Entry) iterator.next();
			if(pathMatcher.match((String)entry.getKey(), s)){
				return (Endpoint) entry.getValue();
			}
		}
		
		return null;
	}
	
	protected abstract String getURIString(ChannelContext<Request, Response> channelContext);

}
